import fetch from 'dva/fetch';
let index = 0;
const BASE_URL = 'http://gateway.supercanteen.com.cn';
function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}
function getUrlParams() { 
    let url=window.location.href;
    let hongdou = url.indexOf("?");   //检索 
    let str = url.slice(hongdou+1);   //选取 
    let arr = str.split("&");                //分割 
    let result =[]; 
    let obj = {};

    for(let i=0;i<arr.length;i++){
        result = arr[i].split("=");         //分割

        obj[result[0]] = result[1];

    } 
  return obj
}
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const appid =getUrlParams().appid;
  if(!appid) {
    index++;
    if(index==1){
      alert("没有appid");
    }
    return  Promise.resolve({});
  }
  let params = {}
  params.body = options ? JSON.stringify(options) : '{}';
 
  params.method ="POST";
    params.headers = {
　　　　'Content-Type': 'application/json',
        appid:appid,
　　}
  return fetch(BASE_URL + url, params)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => { 
      if(data.resultCode!=0){return ''}
      if(data){
        return { data } 
      }else{
        console.log("获取数据失败")
        return {}
      }
      
    })
    .catch(err => {  
        console.log("获取数据失败")
        return {}  
    });
}
